package com.konsung.ksdc.common.mqtt;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.common.utils.ImageUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.UUID;

/**
 * 创建者     kgh
 * 创建时间   2016/5/30 11:34
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class MqttMsgUtils {
    public static final String MSG_TARGET_TYPE_PERSONAL = "1";
    public static final String MSG_TARGET_TYPE_GROUP = "2";

    public static final String MSG_TYPE_TXT = "1"; // 文本消息
    public static final String MSG_TYPE_VOICE = "2"; // 语音消息
    public static final String MSG_TYPE_PIC = "3"; // 图片消息
    public static final String MSG_TYPE_REQUEST_PASSED = "4"; // 好友验证通过消息
    public static final String MSG_TYPE_REQUEST_RECEIVED = "5"; // 好友申请消息
    public static final String MSG_TYPE_DELETE_CONTACT = "6"; // 删除好友消息
    public static final String MSG_TYPE_WIKI = "7"; // 百科消息
    public static final String MSG_TYPE_REQUEST_GROUP = "8"; // 申请群消息
    public static final String MSG_TYPE_DELETE_GROUP = "9"; // 移除群成员消息

    public static final int MSG_TYPE_START = 0;
    public static final int MSG_TARGET_TYPE_START = 1;
    public static final int MSG_SEND_DATE_START = 2;
    public static final int MSG_USER_ID_START = 16;
    public static final int MSG_CONTENT_START = 48;

    /**
     * 将MQTT二进制消息转换成消息对象
     * content[0] 储存消息类型，字符串值1=文字 2=语音 3=图片
     * content[1] 储存消息目标类型：1=个人，2=群体
     * content[2-15] 储存消息发生日期，如20160502131121
     * content[16-47] 存储联系人32位长度ID，如：c1d32eee008c4f2fbae2b27ff38911ad
     * content[48~+] 储存数据
     * @param topicName 名字
     * @param content 内容
     * @return 客户端数据
     */
    public static MqttMsgBean byteParseMsgBean(String topicName, byte[] content) {

        // 消息类型
        String msgType = new String(Arrays.copyOf(content, MSG_TYPE_START + 1));

        // 消息目标类型
        String msgTargetType = new String(Arrays.copyOfRange(content,
                MSG_TARGET_TYPE_START, MSG_TARGET_TYPE_START + 1));

        // 消息发送日期
        String msgSendDate = new String(Arrays.copyOfRange(content,
                MSG_SEND_DATE_START, MSG_SEND_DATE_START + 14));

        // 消息发送者ID
        String userId = new String(Arrays.copyOfRange(content,
                MSG_USER_ID_START, MSG_USER_ID_START + 32));

        MqttMsgBean msg = new MqttMsgBean();
        msg.setContact(userId);
        msg.setMsgType(msgType);
        msg.setMsgTargetType(msgTargetType);
        msg.setMsgSendDate(msgSendDate);
        //msg.setIsRead("N");
        msg.setTopicName(topicName);

        if (MSG_TYPE_TXT.equals(msgType)) {
            msg.setMsgContent(buildStringContent(content));
        } else if (MSG_TYPE_VOICE.equals(msgType)) {
            msg.setMsgContent(buildVoiceContent(content));
        } else if (MSG_TYPE_PIC.equals(msgType)) {
            msg.setMsgContent(buildPicContent(content));
        } else if (MSG_TYPE_REQUEST_PASSED.equals(msgType)) {
            msg.setMsgContent("");
        } else if (MSG_TYPE_REQUEST_RECEIVED.equals(msgType)) {
            msg.setMsgContent(buildStringContent(content));
        } else if (MSG_TYPE_DELETE_CONTACT.equals(msgType)) {
            msg.setMsgContent(buildStringContent(content));
        } else if (MSG_TYPE_WIKI.equals(msgType)) {
            msg.setMsgContent(buildStringContent(content));
        } else {
            Log.e("MqttMsgUtils", "消息类型错误，本条已经忽略！");
        }
        return msg;
    }

    /**
     * 构建文本消息内容
     * @param content 内容
     * @return 消息内容
     */
    public static String buildStringContent(byte[] content) {
        return new String(Arrays.copyOfRange(content, MSG_CONTENT_START, content
                .length));
    }

    /**
     * 构建图片消息
     * @param content 内容
     * @return 图片内容
     */
    public static String buildPicContent(byte[] content) {
        byte[] pic = Arrays.copyOfRange(content, MSG_CONTENT_START, content.length);
        String picName = UUID.randomUUID().toString();

        File file = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath(), picName);

        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(pic);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return file.getPath();
    }

    /**
     * 构建语音消息
     * @param content 内容
     * @return 声音内容
     */
    public static String buildVoiceContent(byte[] content) {
        byte[] voiceContent = Arrays.copyOfRange(content, MSG_CONTENT_START,
                content.length);
        String voiceName = UUID.randomUUID().toString() + ".amr";
        File file = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath(), voiceName);

        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(voiceContent);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file.getPath();
    }

    /**
     * 将消息实体转换成二进制数组
     * content[0] 储存消息类型，字符串值1=文字 2=语音 3=图片
     * content[1] 储存消息目标类型：1=个人，2=群体
     * content[2-15] 储存消息发生日期，如20160502131121
     * content[16-47] 存储联系人32位长度ID，如：c1d32eee008c4f2fbae2b27ff38911ad
     * content[48~+] 储存数据
     * @param bean 数据
     * @return 二进制数据
     */
    public static byte[] msgBeanParseByte(MqttMsgBean bean) {
        String header = bean.getMsgType() + bean.getMsgTargetType()
                + bean.getMsgSendDate() + bean.getContact();

        // 如果是文本消息，则直接返回文本消息数据
        if (MSG_TYPE_TXT.equals(bean.getMsgType())) {
            header = header + bean.getMsgContent();
            return header.getBytes();
        }
        if (MSG_TYPE_REQUEST_RECEIVED.equals(bean.getMsgType())) {
            header = header + bean.getMsgContent();
            return header.getBytes();
        }
        if (MSG_TYPE_DELETE_CONTACT.equals(bean.getMsgType())) {
            header = header + bean.getMsgContent();
            return header.getBytes();
        }

        // 如果文件不存在，则返回空消息
        File f = new File(bean.getMsgContent());
        if (!f.exists() || !f.isFile()) {
            return (header + "").getBytes();
        }

        // 图片压缩后上传
        ImageUtils imageUtils = new ImageUtils();
        if (MSG_TYPE_PIC.equals(bean.getMsgType())) {
            Bitmap bitmap = imageUtils.ratio(bean.getMsgContent());
            byte[] bytes = imageUtils.getBitmapByte(bitmap);
            return byteArrayConcat(header.getBytes(), bytes);
        }

        // 读取语音）
        InputStream in = null;
        byte[] buffer = new byte[(int) f.length()];
        try {
            in = new FileInputStream(f);
            in.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return byteArrayConcat(header.getBytes(), buffer);
    }

    /**
     * 字节数组合并
     * @param arr1 字节
     * @param arr2 字节
     * @return 数组数据
     */
    public static byte[] byteArrayConcat(byte[] arr1, byte[] arr2) {
        byte[] result = new byte[arr1.length + arr2.length];
        System.arraycopy(arr1, 0, result, 0, arr1.length);
        System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
        return result;
    }
}
